package edu.ccut.saturn.basecomponent.database;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * 
 * @author Tony Yan
 * 
 */
public class SaturnSQLBuilderFactory {
	
	public static final String ORACLE = "oracle";
	
	public static final String DB2 = "db2";
	
	public static final String MYSQL = "mysql";
	
	public static final String SQLSERVER = "sqlserver";
	
	public static final String HSQL = "hsql";
	
	public static  List<String> dbTypeList = new ArrayList<String>();
	
	private static Map<String, ISaturnSQLBuilder> sqlBuilderMap = new HashMap<String, ISaturnSQLBuilder>();

	private static final String DIRECTORY_TYPE_FILE_NAME = "builder.properties";
	
	static {
		intialBuilder();
		intialDBList();
	}

	private static void intialBuilder() {
		Properties properties = new Properties();
		InputStream in = null;

		try {
			in = SaturnSQLBuilderFactory.class
					.getResourceAsStream(DIRECTORY_TYPE_FILE_NAME);

			properties.load(in);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		for (Enumeration<?> propertyNames = properties.propertyNames(); propertyNames
				.hasMoreElements();) {

			String key = (String) propertyNames.nextElement();
			String className = properties.getProperty(key);

			try {
				Object builder = Class.forName(className).newInstance();
				
				if (builder instanceof ISaturnSQLBuilder) {
					sqlBuilderMap.put(key, (ISaturnSQLBuilder)builder);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private static void intialDBList() {
		dbTypeList.add(SQLSERVER);
		dbTypeList.add(MYSQL);
		dbTypeList.add(ORACLE);
		dbTypeList.add(DB2);
		dbTypeList.add(HSQL);
	}

	private SaturnSQLBuilderFactory() {
            
	}

	public static ISaturnSQLBuilder getSaturnSQLBuilder(String key) {
		return sqlBuilderMap.get(key);
	}
}
